import cv2
import numpy as np


def tensor_error_threshold(masks, tau=0.25):
    masks[masks >= tau] = 1.
    masks[masks < tau] = 0.
    return masks.long()


def ndarray_error_threshold(masks, tau=0.25):
    masks[masks >= tau] = 1.
    # masks[masks < tau] = 0.
    return np.array(masks, dtype=np.uint8)


def crop_and_resize(mask_output, image, interpolation_down=cv2.INTER_AREA, interpolation_up=cv2.INTER_CUBIC):
    size = mask_output.shape[0]
    h, w = image.shape[:2]
    if w > h:
        scale = size / w
        h_scale = h * scale
        # w_scale = size
        start, end = int((size - h_scale) / 2), int((size - h_scale) / 2 + h_scale)
        mask_output = mask_output[start: end, :]
    else:
        scale = size / h
        w_scale = w * scale
        # h_scale = size
        start, end = int((size - w_scale) / 2), int((size - w_scale) / 2 + w_scale)
        mask_output = mask_output[:, start: end]
    interpolation = interpolation_up if scale > 1 else interpolation_down
    mask_output = cv2.resize(mask_output, (int(w), int(h)), interpolation=interpolation)
    return mask_output
